package org.boot.ssm.wxshop.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.boot.ssm.wxshop.common.impl.BaseServiceImpl;
import org.boot.ssm.wxshop.domain.*;
import org.boot.ssm.wxshop.exception.BusinessException;
import org.boot.ssm.wxshop.mapper.GoodsMapper;
import org.boot.ssm.wxshop.mapper.OrderInfoMapper;
import org.boot.ssm.wxshop.service.*;
import org.boot.ssm.wxshop.util.RandomUtil;
import org.boot.ssm.wxshop.web.common.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderInfoServiceImpl extends BaseServiceImpl<OrderInfo> implements OrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderInfoDetailService orderInfoDetailService;
    @Autowired
    private ReceiveAddressService receiveAddressService;
    @Autowired
    private ShopCarService shopCarService;

    @Override
    /*****************************
     * @Description: 根据条件分页查询
     * @Param: [pageNum, pageSize, override, firstTime, lastTime]
     * @return: com.github.pagehelper.PageInfo<org.boot.ssm.wxshop.domain.OrderInfo>
     * @Author: 刘涛
     * @Date: 2018/3/15
     *******************************/
    public PageInfo<OrderInfo> selectOrderInfoForPage(Integer pageNum, Integer pageSize, OrderInfo orderInfo, String firstTime, String lastTime) {
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<OrderInfo> pageInfo = new PageInfo<>(orderInfoMapper.selectOrderInfoForPage(orderInfo, firstTime, lastTime));
        return pageInfo;
    }

    @Override
    /*****************************
     * @Description: 修改订单状态
     * @Param: [orderInfo]
     * @return: org.boot.ssm.wxshop.web.common.JsonResult
     * @Author: 刘涛
     * @Date: 2018/3/16
     *******************************/
    public JsonResult updateState(OrderInfo orderInfo) {
        Integer isState;
        if (orderInfo.getState() == 0) {
            orderInfo.setState(1);
            orderInfo.setPayTime(new Date());
            isState = this.updateNoNull(orderInfo);
            if (isState == 1) {
                return new JsonResult(200, "付款成功");
            } else {
                throw new BusinessException("付款异常");
            }
        }
        if (orderInfo.getState() == 1) {
            orderInfo.setState(2);
            orderInfo.setDeliveryTime(new Date());
            isState = this.updateNoNull(orderInfo);
            if (isState == 1) {
                return new JsonResult(200, "操作成功");
            } else {
                throw new BusinessException("操作异常");
            }
        }
        if (orderInfo.getState() == 2) {
            orderInfo.setState(3);
            orderInfo.setReceivingTime(new Date());
            isState = this.updateNoNull(orderInfo);
            if (isState == 1) {
                return new JsonResult(200, "已签收");
            } else {
                throw new BusinessException("操作异常");
            }
        }
        if (orderInfo.getState() == 3) {
            orderInfo.setState(4);
            orderInfo.setIsComment(1);
            isState = this.updateNoNull(orderInfo);
            if (isState == 1) {
                return new JsonResult(200, "已评论");
            } else {
                throw new BusinessException("操作异常");
            }
        }
        return null;
    }

    @Override
    @Transactional
    /*****************************
     * @Description: 批量发货
     * @Param: [list]
     * @return: org.boot.ssm.wxshop.web.common.JsonResult
     * @Author: 刘涛
     * @Date: 2018/3/16
     *******************************/
    public JsonResult updateStateMore(List<OrderInfo> list) {
        boolean flag = true;
        for (OrderInfo orderInfo : list) {
            if (orderInfo.getState() == 1) {
                orderInfo.setState(2);
                this.updateNoNull(orderInfo);
            } else {
                flag = false;
                break;
            }
        }
        if (flag) {
            return new JsonResult(200, "批量操作成功");
        } else {
            throw new BusinessException("无法为其他状态订单进行发货操作");
        }
    }

    /**
     * 根据用户，订单状态查询所有订单及详情
     *
     * @param id
     * @param state
     * @return
     */
    @Override
    public JsonResult selectOrderInfoAndDetil(Integer id, Integer state) {
        return new JsonResult(200, "加载成功", orderInfoMapper.selectOrderInfoAndDetil(id, state));
    }

    /**
     * 根据状态以及用户ID查询订单记录条数
     *
     * @param orderInfo
     * @param userId
     * @return
     */
    @Override
    public JsonResult countState(OrderInfo orderInfo, Integer userId) {
        orderInfo.setIsDelete(1);
        orderInfo.setUserId(userId);
        return new JsonResult(200, "加载成功", this.queryCount(orderInfo));
    }


    /**
     * 根据订单号及用户ID查询单个订单
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    public OrderInfo selectOneOrder(String id, Integer userId) {
        return orderInfoMapper.selectOneOrderByIdAndUserId(id, userId);
    }


    /**
     * 逻辑删除订单
     *
     * @param orderInfo
     * @return
     */
    @Override
    public JsonResult deleteOrder(OrderInfo orderInfo) {
        orderInfo.setIsDelete(0);
        Integer isDelete = this.updateNoNull(orderInfo);
        if (isDelete == 1) {
            return new JsonResult(200, "删除成功");
        } else {
            return new JsonResult(500, "删除失败");
        }
    }


    /**
     * 添加单个商品订单
     *
     * @param goodsId
     * @param specifications
     * @return
     */
    @Override
    public JsonResult addOrderForOneGoods(Integer goodsId, String specifications, Integer userId) {
        Goods goods = goodsService.queryById(goodsId);
        if (goods != null) {
            OrderInfo orderInfo = new OrderInfo();
            OrderInfoDetail orderInfoDetail = new OrderInfoDetail();
            ReceiveAddress receiveAddress = new ReceiveAddress();
            //获取默认收获地址
            receiveAddress.setUserId(userId);
            receiveAddress.setIsDefault(1);
            receiveAddress = receiveAddressService.queryByParam(receiveAddress);
            //添加订单
            orderInfo.setAddressId(receiveAddress.getId());
            orderInfo.setState(0);
            orderInfo.setFreight(goods.getFreight());
            orderInfo.setMoney(goods.getPrice() + goods.getFreight());
            orderInfo.setUserId(userId);
            orderInfo.setNo(RandomUtil.getRandomOrderNum());
            this.saveNoNull(orderInfo);
            //添加订单详情
            orderInfoDetail.setOrderInfoId(orderInfo.getId());
            orderInfoDetail.setGoodsId(goods.getId());
            orderInfoDetail.setGoodsImg(goods.getCoverimg());
            orderInfoDetail.setPrice(goods.getPrice());
            orderInfoDetail.setTitle(goods.getTitle());
            orderInfoDetail.setNum(1);
            orderInfoDetail.setSpecificationsInfo(specifications);
            orderInfoDetail.setCountMoney(goods.getPrice());
            orderInfoDetailService.saveNoNull(orderInfoDetail);
            return new JsonResult(200, "添加订单成功", orderInfo.getId());
        } else {
            return new JsonResult(500, "商品信息已更改");
        }
    }


    /**
     * 添加多个商品的订单
     *
     * @param carIds
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public JsonResult addOrderForMoreGoods(Integer[] carIds, Integer userId) {
        if(carIds.length>=0){
            //获取默认收获地址
            ReceiveAddress receiveAddress = new ReceiveAddress();
            receiveAddress.setUserId(userId);
            receiveAddress.setIsDefault(1);
            receiveAddress = receiveAddressService.queryByParam(receiveAddress);
            //添加订单
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setState(0);
            orderInfo.setUserId(userId);
            orderInfo.setNo(RandomUtil.getRandomOrderNum());
            orderInfo.setAddressId(receiveAddress.getId());
            //获取总金额及邮费
            Double sumPrice = 0.0;
            Double freight = 0.0;
            for (int i = 0; i < carIds.length; i++) {
                ShopCar shopCar = shopCarService.queryById(carIds[i]);
                Goods goods = goodsService.queryById(shopCar.getGoodsId());
                sumPrice += shopCar.getPrice() * shopCar.getNum();
                if (i > 0) {
                    if (freight < goods.getFreight()) {
                        freight = goods.getFreight();
                    }
                } else {
                    freight = goods.getFreight();
                }
            }
            orderInfo.setFreight(freight);
            orderInfo.setMoney(sumPrice + freight);
            this.saveNoNull(orderInfo);
            //添加订单详情
            OrderInfoDetail orderInfoDetail = new OrderInfoDetail();
            for (int i = 0; i < carIds.length; i++) {
                ShopCar shopCar = shopCarService.queryById(carIds[i]);
                orderInfoDetail.setId(null);
                orderInfoDetail.setOrderInfoId(orderInfo.getId());
                orderInfoDetail.setGoodsId(shopCar.getGoodsId());
                orderInfoDetail.setGoodsImg(shopCar.getGoodsImg());
                orderInfoDetail.setPrice(shopCar.getPrice());
                orderInfoDetail.setTitle(shopCar.getTitle());
                orderInfoDetail.setNum(shopCar.getNum());
                orderInfoDetail.setSpecificationsInfo(shopCar.getSpecificationsInfo());
                orderInfoDetail.setCountMoney(shopCar.getPrice()*shopCar.getNum());
                Integer isAdd = orderInfoDetailService.saveNoNull(orderInfoDetail);
                if(isAdd==1){
                    shopCar.setIsDelete(0);
                    shopCarService.updateNoNull(shopCar);
                }else {
                    throw new BusinessException("订单系统异常,请稍后再试");
                }
            }
            return new JsonResult(200, "添加订单成功", orderInfo.getId());
        }else {
            return new JsonResult(500, "请选择商品");
        }
    }

}
